// pages/productDetail/productDetail.js
var app = getApp()
import Toast from '@vant/weapp/toast/toast';
Page({
  /**
   * 页面的初始数据
   */
  data: {
    openid: "",
    id: 0,
    evaluate: [],
    collectionId: "",
    show: false,
    productDetail: {},
    collection: false,
    specification: "",
    nIndex: 0,
    price: 0,
    num: 1,
    cartNum: 0,
    showCartNum: false,
    addToCart: false,
    buyNow: false,
    order: {}
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //获取首页点击推荐产品的id
    this.setData({
      id: options.id,
      openid: wx.getStorageSync('userInfo').openid
    })
    this.getProductDetail()
    this.getEvaluate()
    this.getCollection()
    this.getCartNum()
    // Toast('我是提示文案，建议不超过十五字~');
  },
  //确定收藏
  enterCollection() {
    let collectionDetail = this.data.productDetail
    //判断是否登录
    if (!this.data.openid) {
      wx.showToast({
        title: "请先登录",
        icon: "none"
      })
    } else {
      this.setData({
        collection: !this.data.collection,
      })
      if (this.data.collection) {
        app.db('collection')
          .add({
            data: {
              id: collectionDetail._id,
              name: collectionDetail.name,
              price_first: collectionDetail.price_first,
              image: collectionDetail.image,
              sale: collectionDetail.sale,
              gross: collectionDetail.gross
            }
          })
          .then(res => {
            console.log('插入成功', res)
            Toast('收藏成功');
            this.getCollection()
          })
          .catch(err => {
            console.log('插入失败', err)
          })

      } else {
        app.removeOne('collection', this.data.collectionId)
          .then(res => {
            console.log('删除成功', res)
            Toast('取消收藏成功');
          })
          .catch(err => {
            console.log('删除失败', err)
          })
      }
    }
  },
  getProductDetail() {
    app.getOne('product_details', this.data.id)
      .then(res => {
        console.log("获取成功", res)
        this.setData({
          productDetail: res.data,
          price: res.data.price[0],
          specification: res.data.specification[0]
        })
      })
      .catch(err => {
        console.log("获取失败", err)
      })
  },
  getEvaluate() {
    app.getOne("evaluate", this.data.id)
      .then(res => {
        this.setData({
          evaluate: res.data.evaluate
        })
      })
  },
  //查询购物车中商品数量
  getCartNum() {
    if (wx.getStorageSync('userInfo')) {
      app.getList('cart')
        .then(res => {
          console.log("购物车中商品数量为", res.data.length)
          if (res.data.length > 0) {
            this.setData({
              cartNum: res.data.length,
              showCartNum: true,
              show: false
            })
          }
        })
    } else {
      // 不做处理
    }
  },
  //在收藏表中查询是否存在此商品
  getCollection() {
    //判断是否登录
    if (!this.data.openid) {
      wx.showToast({
        title: "请先登录",
        icon: "none"
      })
    } else {
      app.db('collection')
        .where({
          id: this.data.id
        })
        .get()
        .then(res => {
          this.setData({
            collection: true,
            collectionId: res.data[0]._id
          })
          console.log('请求成功', res.data)
        })
        .catch(err => {
          console.log('请求失败', err)
        })
    }
  },
  //跳转到购物车
  goToCart() {
    wx.switchTab({
      url: '../cart/cart',
    })
  },
  addToCartChoose() {
    //判断是否登录
    if (!this.data.openid) {
      wx.showToast({
        title: "请先登录",
        icon: "none"
      })
    } else if (this.data.productDetail.gross == this.data.productDetail.sale) {
      wx.showToast({
        title: "抱歉，此商品暂时无货",
        icon: "none"
      })
    } else {
      this.setData({
        addToCart: true,
        buyNow: false
      })
      this.showPopup()
    }
  },
  showPopup() {
    this.setData({
      show: true
    });
  },
  onClose() {
    this.setData({
      show: false
    });
  },
  chooseSpecification(e) {
    this.setData({
      nIndex: e.currentTarget.dataset.index,
      specification: e.currentTarget.dataset.specification,
      price: this.data.productDetail.price[e.currentTarget.dataset.index]
    })
  },
  onNumChange(e) {
    this.setData({
      num: e.detail
    })
    console.log(e.detail)
  },
  addToCart() {
    let cartDetail = this.data.productDetail
    const _ = wx.cloud.database().command
    //查找购物车中有无同id同规格的物品
    app.db('cart')
      .where(_.and([{
        id: this.data.id,
      }, {
        specificationNow: this.data.specification
      }]))
      .get()
      .then(res => {
        console.log('请求成功', res.data)
        //如果有则增加其数量
        if (res.data.length == 1) {
          app.db("cart").doc(res.data[0]._id).update({
              data: {
                count: res.data[0].count + this.data.num
              }
            })
            .then(res => {
              console.log("添加成功", res)
              wx.showToast({
                title: '添加成功',
              })
            })
            .catch(err => {
              console.log("添加失败", err)
              wx.showToast({
                title: '添加失败，请稍后重试',
                icon: "error"
              })
            })
          //如果没有则新增
        } else {
          app.db('cart')
            .add({
              data: {
                id: cartDetail._id,
                state: false,
                name: cartDetail.name,
                imgSrc: cartDetail.image,
                price: this.data.price,
                count: this.data.num,
                specificationNow: this.data.specification,
                specification: cartDetail.specification,
                index: this.data.nIndex
              }
            })
            .then(res => {
              wx.showToast({
                title: '添加成功',
              })
              this.setData({
                cartNum: this.data.cartNum + 1
              })
              console.log('添加成功', res)
            })
            .catch(err => {
              console.log('添加失败', err)
              wx.showToast({
                title: '添加失败，请稍后重试',
                icon: "error"
              })
            })
        }
      })
    this.getCartNum()
  },
  buyNow() {
    //判断是否登录
    if (!this.data.openid) {
      wx.showToast({
        title: "请先登录",
        icon: "none"
      })
    } else if (this.data.productDetail.gross == this.data.productDetail.sale) {
      wx.showToast({
        title: "抱歉，此商品暂时无货",
        icon: "none"
      })
    } else {
      this.setData({
        addToCart: false,
        buyNow: true
      })
      this.showPopup()
    }
  },
  showPopup() {
    this.setData({
      show: true
    });
  },
  // 跳转支付页面    
  goToPay() {
    let productDetail = this.data.productDetail
    let order = {}
    order.id = productDetail._id,
      order.state = false,
      order.name = productDetail.name,
      order.imgSrc = productDetail.image,
      order.price = this.data.price,
      order.count = this.data.num,
      order.specificationNow = this.data.specification,
      order.specification = productDetail.specification,
      order.index = this.data.nIndex
    this.setData({
      order: order
    })
    wx.setStorageSync('goods', [order])
    wx.navigateTo({
      url: '/pages/payinfo/payinfo?total=' + productDetail.price[this.data.nIndex] * this.data.num + "&type=" + 1,
    })
  },
  goToEvaluate() {
    wx.navigateTo({
      url: '../../pages/evaluate/evaluate?id=' + this.data.id,
    })
  }
})